package app.udp;

/**
 *
 * @author Pedro Santos
 */
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JTextArea;

public class ServerUdp implements Runnable {

    Thread thread;
    DatagramSocket socket;
    InetAddress client; // Endereço do Cliente.
    int client_port; // Port do cliente.    

    public ServerUdp() {        
       thread = new Thread(this);
       thread.start();//REVER        
    }

    @Override
    public void run() {
        try {
            byte[] buffer = new byte[1024];
            int port = 8080;
            try {
                socket = new DatagramSocket(port);
                while (true) {
                    try {
                   //     area.append("Servidor Iniciado!\n");
                        //Recebe requisição do cliente.
                        System.out.println("Server ON!");                        
                        DatagramPacket packet =
                                new DatagramPacket(buffer, buffer.length);
                        System.out.println("Aguardando Requisição!");
                        socket.receive(packet);  
                        System.out.println("RECEBEU!");
                        client = packet.getAddress();
                        client_port = packet.getPort();                        

                    } catch (UnknownHostException ue) {
                    }
                }
            } catch (java.net.BindException b) {
            }
        } catch (IOException e) {
            System.err.println(e);
        }

    }

    public void off() {
        thread.interrupted();
        socket.close();
    }

    public InetAddress getClient() {
        return client;
    }

    public void setClient(InetAddress client) {
        this.client = client;
    }

    public int getClient_port() {
        return client_port;
    }

    public void setClient_port(int client_port) {
        this.client_port = client_port;
    }
}
